﻿using System;
using System.Collections.Generic;
using System.Windows.Forms;
using System.IO;

namespace m3uGen
{
    public partial class m3uGenForm : Form
    {
        string[] filter;

        public m3uGenForm()
        {
            InitializeComponent();
        }

        private string GetLastDirName(string str)
        {
            int index = str.LastIndexOf('\\') + 1;
            return str.Substring(index);
        }

        private void EnumSubDirectories(string dir, TreeNode node)
        {
            node.Nodes.Clear();
            DirectoryInfo di = new DirectoryInfo(dir);
            DirectoryInfo[] subDirInfos = di.GetDirectories();
            int i = 0;
            foreach (DirectoryInfo subdir in subDirInfos)
            {
                TreeNode tnode = new TreeNode(subdir.Name);
                tnode.Checked = node.Checked;
                if (!subdir.Name.Equals("System Volume Information"))
                {
                    node.Nodes.Add(tnode);
                    DirectoryInfo[] subDirs = subdir.GetDirectories();
                    if (subDirs.Length > 0)
                        node.Nodes[i].Nodes.Add(subDirs[0].Name);
                    i++;
                }
            }
        }

        private string GetFullPath(TreeNode node)
        {
            string str = "";
            if (node.Parent == null)
                return node.Text;
            str = GetFullPath(node.Parent);
            str += '\\' + node.Text;
            return str;
        }

        private void SubNodeCheck(TreeNode node)
        {
            foreach (TreeNode tn in node.Nodes)
            {
                tn.Checked = node.Checked;
                //SubNodeCheck(tn);
            }
        }

        private void OpenFolder(bool bAdd)
        {
            FolderBrowserDialog fbd = new FolderBrowserDialog();
            DialogResult result = fbd.ShowDialog();
            if (result == DialogResult.OK)
            {
                string foldername = fbd.SelectedPath;
                if (!bAdd)
                    treevFolderTree.Nodes.Clear();
                treevFolderTree.Nodes.Add(foldername);
                EnumSubDirectories(foldername, treevFolderTree.Nodes[treevFolderTree.Nodes.Count - 1]);
            }
        }

        private string[] FileNameFilter(FileInfo[] fileNameArray, string[] filter)
        {
            List<string> strList = new List<string>();
            foreach (FileInfo file in fileNameArray)
            {
                for (int i = 0; i < filter.Length; i++)
                    if (file.Extension.Equals(filter[i]))
                    {
                        strList.Add(file.Name);
                        break;
                    }
            }
            return strList.ToArray();
        }

        private void qsort(List<string> s_arr, List<string> work_arr, int first, int last)
        {
            int i = first, j = last;
            string x = s_arr[(first + last) / 2];

            do
            {
                if (поВозрастаниюToolStripMenuItem.Checked)
                {
                    while (s_arr[i].CompareTo(x) < 0) i++;
                    while (s_arr[j].CompareTo(x) > 0) j--;
                }
                else
                {
                    while (s_arr[i].CompareTo(x) > 0) i++;
                    while (s_arr[j].CompareTo(x) < 0) j--;
                }

                if (i <= j)
                {
                    if (i < j)
                    {
                        string buf = s_arr[i];
                        s_arr[i] = s_arr[j];
                        s_arr[j] = buf;
                        buf = work_arr[i];
                        work_arr[i] = work_arr[j];
                        work_arr[j] = buf;
                    }
                    i++;
                    j--;
                }
            } while (i <= j);

            if (i < last)
                qsort(s_arr, work_arr, i, last);
            if (first < j)
                qsort(s_arr, work_arr, first, j);
        }

        private string[] SortFileNames(List<string> files)
        {
            List<string> fileNames = new List<string>();
            foreach (string buf in files)
                fileNames.Add(GetLastDirName(buf));

            qsort(fileNames, files, 0, files.Count - 1);

            return files.ToArray();
        }

        private void SavePlaylist(string fileName, string[] files)
        {
            StreamWriter swriter = new StreamWriter(new FileStream(fileName, FileMode.Create, FileAccess.Write, FileShare.None), System.Text.Encoding.UTF8);
            swriter.WriteLine("#EXTM3U");
            foreach (string file in files)
                swriter.WriteLine(file);
            swriter.Close();
        }

        private string[] GetFileList(TreeNode node)
        {
            List<string> AllFiles = new List<string>();
            string[] strs;
            foreach (TreeNode tr in node.Nodes)
            {
                if (tr.Checked)
                {
                    EnumSubDirectories(GetFullPath(tr), tr);
                    strs = GetFileList(tr);
                    foreach (string buf in strs)
                        AllFiles.Add(tr.Text + "\\" + buf);
                }
            }
            string FullPath = GetFullPath(node);
            DirectoryInfo di = new DirectoryInfo(FullPath);
            FileInfo[] filesInfo = di.GetFiles();
            string[] fileNames = FileNameFilter(filesInfo, filter);
            foreach (string tmp in fileNames)
                AllFiles.Add(tmp);
            if (AllFiles.Count > 0)
            {
                string tempStr = node.Text;
                if (node.Parent == null)
                    tempStr = GetLastDirName(FullPath);

                string[] sortedList = AllFiles.ToArray();
                if (!нетToolStripMenuItem.Checked)
                    sortedList = SortFileNames(AllFiles);
                SavePlaylist(FullPath + "\\" + tempStr + ".m3u", sortedList);
                tboxSavedFiles.Text += FullPath + "\\" + tempStr + ".m3u\r\n";
            }

            return AllFiles.ToArray();
        }

        private void открытьПапкуToolStripMenuItem_Click(object sender, EventArgs e)
        {
            OpenFolder(false);
        }

        private void выходToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Close();
        }

        private void treevFolderTree_BeforeExpand(object sender, TreeViewCancelEventArgs e)
        {
            if (e.Node.Parent != null)
                EnumSubDirectories(GetFullPath(e.Node), e.Node);
        }

        private void treevFolderTree_AfterCheck(object sender, TreeViewEventArgs e)
        {
            SubNodeCheck(e.Node);
        }

        private void добавитьПапкуToolStripMenuItem_Click(object sender, EventArgs e)
        {
            OpenFolder(true);
        }

        private void создатьToolStripMenuItem_Click(object sender, EventArgs e)
        {
            filter = textBox1.Text.Split(';');
            tboxSavedFiles.Text = "";
            foreach (TreeNode tr in treevFolderTree.Nodes)
                GetFileList(tr);
        }

        private void нетToolStripMenuItem_Click(object sender, EventArgs e)
        {
            нетToolStripMenuItem.Checked = true;
            поВозрастаниюToolStripMenuItem.Checked = false;
            поУбываниюToolStripMenuItem.Checked = false;
        }

        private void поВозрастаниюToolStripMenuItem_Click(object sender, EventArgs e)
        {
            поВозрастаниюToolStripMenuItem.Checked = true;
            нетToolStripMenuItem.Checked = false;
            поУбываниюToolStripMenuItem.Checked = false;
        }

        private void поУбываниюToolStripMenuItem_Click(object sender, EventArgs e)
        {
            поУбываниюToolStripMenuItem.Checked = true;
            нетToolStripMenuItem.Checked = false;
            поВозрастаниюToolStripMenuItem.Checked = false;
        }
    }
}
